package cn.turboinfo.dongying.api.provider.admin.framework.shiro.filter;

import cn.turboinfo.dongying.api.entity.admin.enumeration.login.AdminLoginOperation;
import cn.turboinfo.dongying.api.provider.admin.component.session.AdminSessionHelper;
import cn.turboinfo.dongying.api.provider.admin.framework.shiro.session.AdminSession;
import cn.turboinfo.dongying.api.provider.admin.component.session.AdminSessionHelper;
import cn.turboinfo.dongying.api.provider.admin.framework.shiro.session.AdminSession;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

@RequiredArgsConstructor
public class LoginOperationAuthenticationFilter extends AuthenticationFilter {

    private final AdminSessionHelper adminSessionHelper;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        if (subject.isAuthenticated() && subject.getPrincipal() != null) {
            AdminSession session = adminSessionHelper.getSession();
            if (session.getLoginOperation() == AdminLoginOperation.MODIFY_PASSWORD) {
                // 如果要求强制修改密码不允许继续
                return false;
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        saveRequest(request);
        // 跳转到强制修改密码页面
        WebUtils.issueRedirect(request, response, "/admin/sysUser/forceModifyPassword");
        return false;
    }

}
